<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;
use \Workerman\MySQL\Connection;
//require_once '/your/path/of/mysql-master/src/Connection.php';

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
    /**
     * 新建一个类的静态成员，用来保存数据库实例
     */
    public static $db = null;
    public static $redis=null;
    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart(){
        self::$db = new \Workerman\MySQL\Connection('127.0.0.1', '3306', 'zhibo_zhipall_cn', 'HweFpT5SyWb53hWj', 'zhibo_zhipall_cn');
        self::$redis = new redis();
        self::$redis->connect('127.0.0.1', 6379);
    }
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
//        // 向当前client_id发送数据
//        Gateway::sendToClient($client_id, "Hello $client_id\r\n");
//        // 向所有人发送
//        Gateway::sendToAll("$client_id login\r\n");
    }
    
   /**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
   public static function onMessage($client_id, $message)
   {
       echo $message;
       $message = json_decode($message, true);
       switch($message['type']) {
           case 'init'://初始化
                //绑定UID用户
                Gateway::bindUid($client_id, $message['uid']);
                //加入直播群组
                Gateway::joinGroup($client_id,$message['stream']);
                //发送消息
                Gateway::sendToGroup($message['stream'],json_encode([
                    'type'=>'chat',
                    'sort'=>2,
                    'content'=>$message['nickname'].'来了',
                    'nickname'=>'系统消息'
                ]));
                //查询观看人
                $userList=self::$db->query("SELECT b.id,b.nickname,b.avatar FROM `zp_live_view` a,`zp_user` b WHERE a.uid=b.id and a.is_line=1 and a.live_id=".$message['live_id']);
                //查询观看人数
                $viewNum=self::$db->select('views')->from('zp_live')->where("id=".$message['live_id'])->single();
                Gateway::sendToGroup($message['stream'],json_encode([
                   'type'=>'views',
                   'nums'=>$viewNum,
                   'list'=>$userList
                ]));
               break;
           case 'chat'://聊天消息
               Gateway::sendToGroup($message['stream'],json_encode([
                   'type'=>'chat',
                   'sort'=>1,
                   'content'=>$message['content'],
                   'nickname'=>$message['nickname']
               ]));
               break;
           case 'follow'://关注人数
               $follows=self::$db->select('g_nums')->from('zp_live')->where("id=".$message['live_id'])->single();
               Gateway::sendToGroup($message['stream'],json_encode([
                   'type'=>'follow',
                   'g_nums'=>$follows
               ]));
               break;
           case 'zans'://点赞人数
               $zans=self::$db->select('zans')->from('zp_live')->where("id=".$message['live_id'])->single();
               Gateway::sendToGroup($message['stream'],json_encode([
                   'type'=>'zans',
                   'zans'=>$zans
               ]));
               break;
           case 'quit'://退出房间
               //发送消息
               Gateway::sendToGroup($message['stream'],json_encode([
                   'type'=>'chat',
                   'sort'=>2,
                   'content'=>$message['nickname'].'走了',
                   'nickname'=>'系统消息'
               ]));
               break;
           case 'initChat':
               #绑定UID用户
               Gateway::bindUid($client_id, $message['uid']);
               #未接收聊天信息
               $list=self::$redis->hGetAll($message['uid']);//获取该用户redis所有未处理信息
               foreach($list as $key => $value){
                   $data = json_decode($value,true);
                   Gateway::sendToUid($data['to_uid'],json_encode([
                       'type'=>'msgsList',
                       'data'=>$data
                   ]));
               }
               break;
           case 'msgs'://客服聊天消息 #消息格式{type: "msgs", data: {type: 1, to_uid: 1, content: {text: "dddd"}, from_uid: 2,…}}
               $data=$message['data'];
               if(!empty($data['to_uid'])){
                   #判断用户是否在线
                   $is_online=Gateway::isUidOnline($data['to_uid']);
                   if($is_online){
                       Gateway::sendToUid($data['to_uid'],json_encode([
                           'type'=>'msgs',
                           'data'=>$data
                       ]));
                   }else{#redis 儲存
                       self::$redis->hSet($data['to_uid'],$data['id'],json_encode($data));
                   }
               }
               break;
       }
       // 向所有人发送
        //Gateway::sendToAll("$client_id said $message\r\n");
   }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
   public static function onClose($client_id)
   {
       // 向所有人发送 
       //GateWay::sendToAll("$client_id logout\r\n");
   }
}
